﻿#include "u_quality_time_chart.h"

QualityTimeChart::QualityTimeChart(Equipment *equ, QWidget *parent) : MyWidget(parent)
{
    this->equ = equ;

    timer = new QTimer;

    this->InitWidget();
    this->SetupConnections();
    this->Initialize();

    timer->start(500);
}

QualityTimeChart::~QualityTimeChart(){
    timer->stop();
}

void QualityTimeChart::InitWidget(){
//    terminate called after throwing an instance of 'std::bad_alloc'
//      what():  std::bad_alloc

//    QPainter::begin: A paint device can only be painted by one painter at a time.
//    QPainter::translate: Painter not active
//    QPainter::worldTransform: Painter not active

//    QBackingStore::endPaint() called with active painter on backingstore paint device
//    QWidget::repaint: Recursive repaint detected

    series1 = new QSplineSeries();
    series1->setPen(QPen(QColor("#66ff00"),1.5,Qt::SolidLine));

    series2 = new QSplineSeries();
    series2->setPen(QPen(QColor( 244,242,164),1,Qt::SolidLine));

    QDateTimeAxis *axisX = new QDateTimeAxis;
    axisX->setFormat("HH:mm:ss");
    axisX->setLinePenColor("#2993D1");
    axisX->setGridLineColor(QColor("#2993D1"));
    axisX->setLabelsColor(QColor(255,255,255,200));

    QValueAxis *axisY = new QValueAxis;
    axisY->setRange(0, 100);
    axisY->setLabelFormat("%.1f");
    axisY->setLinePenColor("#2993D1");
    axisY->setGridLineColor(QColor("#2993D1"));
    axisY->setLabelsColor(QColor(255,255,255,200));

    chart = new Chart();
    chart->addSeries(series1);
    chart->setAxisX(axisX,series1);
    chart->setAxisY(axisY,series1);
    chart->addSeries(series2);
    chart->setAxisX(axisX,series2);
    chart->setAxisY(axisY,series2);

    ChartView *chartView = new ChartView(chart);

    QVBoxLayout *chartlayout = new QVBoxLayout();
    chartlayout->setMargin(0);
    chartlayout->addWidget(chartView);

    this->setLayout(chartlayout);
}

void QualityTimeChart::SetupConnections(){
    connect(timer, SIGNAL(timeout()), this, SLOT(OnTimer()));
}

void QualityTimeChart::Initialize(){

}

void QualityTimeChart::OnTimer(){

    chart->axisX()->setMin(QDateTime::currentDateTime().addSecs(-120));
    chart->axisX()->setMax(QDateTime::currentDateTime().addSecs(0));

    if(points1.size() > 240){
        points1.remove(0);
    }

    if(points2.size() > 240){
        points2.remove(0);
    }

    double x = QDateTime::currentDateTime().toMSecsSinceEpoch();

//    points1.append(QPointF(x, equ->temp));
//    points2.append(QPointF(x, equ->hum));

//    series1->replace(points1);
//    series2->replace(points2);
}
